//  获取默认的选中信息
// 设置所有的radio值为只读
// 操作人ID
var operateUserId = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID;
//操作人姓名
var operateUserName = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name;
//操作人帐号
var operateAccountName = JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.username;

// 客户组ID
var mainCustomerId = sessionStorage.getItem("mainCustomerId")

// 获取接口数据
var getData = {
    // 订单配置接口
    orderData: function () {
        var params = {
            mainCustomerId: mainCustomerId
        }
        $.ajax({
            type: 'GET',//请求方式get请求
            url: root.member.queryOrderSetup,//请求地址
            data: params,//请求参数客户组id
            //dataType:'json',//数据格式
            timeout: 3000,//请求超时的时间
            cache: false,//是否缓存上一次数据
            async: true,
            success: function (result) {
                console.log(result);
                if (result.errorCode === 0 && result.data !== null) {
                    renderData.orderInfoState(result.data);
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000);
            }
        })
    },
    // 保存订单配置状态
    saveOrderInfo: function (params) {
        /*       var params = {
                   mainCustomerId:mainCustomerId,
                   freightType:'',//运费类型：10-不限；20-单开； 30-分摊
                   paymentMethod:'',//支付方式，逗号拼接：1201-账期支付；1001-在线支付；1301-银行转账；1101-货到付款；全不选-不传或空字符串
                   joinActivity:'',//是否可以参加促销活动：10-可以参加；20-不可参加；全不选-不传或null
                   needQualification:'',//是否要资质：10-需要；20-不需要；全不选-不传或null
                   needRedChapter:'',//是否带红章：10-是；20-否；全不选-不传或null
                   copyNum:'', //资质份数
                   operateUserId:operateUserId,
                   operateUserName:operateUserName,
               }*/
        $.ajax({
            url: root.member.saveOrderSetup,
            cache: false,  //禁用缓存
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify(params),
            success: function (data) {
                if (data.errorCode === 0) {
                    $.Huimodalalert('保存成功', 3000);
                    // 关闭当前页面
                    //parent.layer.closeAll();
                } else {
                    $.Huimodalalert(data.msg, 3000);
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 3000);
            }
        })
    }
}
// 渲染数据
var renderData = {
    //展示订单配置状态
    orderInfoState: function (data) {
        // 运费类型
        var freightType = data.freightType;
        // 支付方式
        var paymentMethod = data.paymentMethod;
        // 参与活动
        var joinActivity = data.joinActivity;
        // 是否要资质
        var needQualification = data.needQualification;
        // 是否带红章
        /* var needRedChapter = data.needRedChapter;*/
        //资质分数
        var copyNum = data.copyNum;
        /*//区域
       /* if(data.priceAreaId!=null){
            $("#priceAreaId").val(data.priceAreaId)
        }*/
        if (data.paymentApprovalCycle != null) {
            $("#paymentApprovalCycle").val(data.paymentApprovalCycle)
        }

        /*    数据回填渲染   */
        // 运费处理
        switch (freightType) {
            case 10:
                $("#radio1").attr("checked", "checked");
                break;
            case 20:
                $("#radio2").attr("checked", "checked");
                break;
            case 30:
                $("#radio3").attr("checked", "checked");
                break;
            default:
                null;
        }
        // 支付方式 1201  账期支付    1001 在线支付  1301 银行转账  1101 货到付款  '' 全部选
        var subSet = function (arr1, arr2) {
            var len = arr1.length;
            var arr = [];
            while (len--) {
                if (arr2.indexOf(arr1[len]) < 0) {
                    arr.push(arr1[len]);
                }
            }
            return arr;
        }
        var payment = paymentMethod.split(',');
        var arr = ['1201', '1001', '1301', '1101']
        $.each(payment, function (index, item) {
            var item1 = Number(item)
            switch (item1) {
                case 1201:
                    $("#checkbox1").attr("checked", "checked");
                    break;
                case 1001:
                    $("#checkbox2").attr("checked", "checked");
                    break;
                case 1301:
                    $("#checkbox3").attr("checked", "checked");
                    break;
                case 1101:
                    $("#checkbox4").attr("checked", "checked");
                    break;
                default:
                    null;
            }
        });
        console.log(payment, arr)
        var diff = subSet(arr, payment)
        console.log(diff)
        $.each(diff, function (index, item) {
            var item1 = Number(item)
            switch (item1) {
                case 1201:
                    $("#checkbox1").attr("checked", false);
                    break;
                case 1001:
                    $("#checkbox2").attr("checked", false);
                    break;
                case 1301:
                    $("#checkbox3").attr("checked", false);
                    break;
                case 1101:
                    $("#checkbox4").attr("checked", false);
                    break;
                default:
                    null;
            }
        });

        // 参与活动 10 可以参加   20 不可参加   null全部选
        switch (joinActivity) {
            case 10:
                $("#radio6").attr("checked", "checked");
                break;
            case 20:
                $("#radio5").attr("checked", "checked");
                break;
            default:
                null;
        }
        // 是否需要资质  20 不展示  10 展示  null全不选
        switch (needQualification) {
            case 10:
                $("#radio8").attr("checked", "checked");
                break;
            case 20:
                $("#radio7").attr("checked", "checked");
                break;
            default:
                null;
        }
        // 是否带红章 10 是  20 否  null 全不选
        /* switch (needRedChapter) {
             case 10 :
                 $("#radio9").attr("checked","checked");
                 break;
             case 20:
                 $("#radio10").attr("checked","checked");
                 break;
             default:
                 null;
         }*/
        // 设置资质份数
        $('#copyNum').val(copyNum);
        $("input[name='mainPassword']").val(data.mainPassword);
        if (data.slideShow == "1") {
            $("#radio11").attr("checked", "checked");
        } else {
            $("#radio10").attr("checked", "checked");
        }
    },
    // 获取 设置的订单配置状态
    getInfoState: function () {
        // 保存的接口入参
        var params = {};
        var payParams = []
        // 获取运费类型
        var freightTypeValue = $(":radio[name='freightType']:checked + label").text();
        // 支付方式
        var paymentMethod1 = $(":checkbox[name='paymentMethod1']:checked + label").text();
        var paymentMethod2 = $(":checkbox[name='paymentMethod2']:checked + label").text();
        var paymentMethod3 = $(":checkbox[name='paymentMethod3']:checked + label").text();
        var paymentMethod4 = $(":checkbox[name='paymentMethod4']:checked + label").text();
        // 参与活动
        var joinActivityValue = $(":radio[name='joinActivity']:checked + label").text();
        // 资质
        var needQualificationValue = $(":radio[name='needqualify']:checked + label").text();
        //红章
        /* var needRedChapterValue = $(":radio[name='redChapter']:checked + label").text();*/
        // 资质份数
        var copyNum = $("#copyNum").val();
        /*    设置参数对应得接口入参    */
        // 运费类型入参
        switch (freightTypeValue) {
            case '不限':
                params.freightType = 10;
                break;
            case '单开':
                params.freightType = 20;
                break;
            case '分摊':
                params.freightType = 30;
                break
            default:
                null;
        }
        // 支付方式
        paymentMethod1 === '账期支付' ? payParams.push(1201) : null
        paymentMethod2 === '在线支付' ? payParams.push(1001) : null
        paymentMethod3 === '线下汇款' ? payParams.push(1301) : null
        paymentMethod4 === '货到付款' ? payParams.push(1101) : null
        params.paymentMethod = payParams.join(',')
        // 参与活动
        switch (joinActivityValue) {
            case '不参加':
                params.joinActivity = 20;
                break;
            case '参加':
                params.joinActivity = 10;
                break;
            default:
                null;
        }
        // 是否需要资质
        switch (needQualificationValue) {
            case '不展示':
                params.needQualification = 20;
                break;
            case '展示':
                params.needQualification = 10;
                break;
            default:
                null;
        }
        // 是否需要红章
        /* switch (needRedChapterValue){
             case '否':
                 params.needRedChapter = 20;
                 break;
             case '是':
                 params.needRedChapter = 10;
                 break;
             default:
                 null;
         }*/
        // 资质份数
        params.copyNum = Number(copyNum)
        // 操作id
        params.operateUserId = operateUserId;
        // 操作姓名
        params.operateUserName = operateUserName;
        // 客户组id、
        params.mainCustomerId = mainCustomerId;
        // 指定价格区域 、
        /*params.priceAreaId = $("#priceAreaId option:selected").val();*/
        // 支付审批周期、
        params.paymentApprovalCycle = $("#paymentApprovalCycle").val();
        params.mainPassword = $("input[name='mainPassword']").val();
        params.slideShow = $("input:radio[name='slideShow']:checked").val();
        return params;
    }
}
// 保存订单配置状态

// 保存信息
function saveOrderState () {
    // 运费类型
    var freightType = $('input:radio[name="freightType"]:checked').val();
    //参与活动
    var joinActivity = $('input:radio[name="joinActivity"]:checked').val();
    // 是否要资质
    var needqualify = $('input:radio[name="needqualify"]:checked').val();
    // 需要资质则份数必填判断
    // 份数
    var num = $("#copyNum").val();
    // 是否带红章
    /*var redChapter = $('input:radio[name="redChapter"]:checked').val();*/
    if (needqualify === "展示") {
        /*  if(redChapter == null){
              $.Huimodalalert('请选择是否带红章',3000);
              return ;
          }*/
        if (num == "" || num == 0) {
            $.Huimodalalert('请输入份数', 3000);
            return;
        }
        if (Number(num) > 100) {
            $.Huimodalalert('输入份数不能超过100份', 3000);
            return;
        }

    }
    // 支付方式
    var payMethod = $(".pay_method");
    var flag = false;
    if (freightType == null) {
        $.Huimodalalert('请选择运费类型', 3000);
    } else if (joinActivity == null) {
        $.Huimodalalert('请选择是否参与活动', 3000);
    } else if (needqualify == null) {
        $.Huimodalalert('请选择是否要资质', 3000);
    } else {
        // 支付方式
        $.each(payMethod, function (index, item) {
            if (item.checked) {
                flag = true;
                return;
            }
        })
        if (!flag) {
            $.Huimodalalert('请选择支付方式', 3000);
            return;
        }
    }
    //支付审批周期
    if ($("#paymentApprovalCycle").val() == "") {
        $.Huimodalalert('请填写支付审批周期', 3000);
        return;
    }

    getData.saveOrderInfo(renderData.getInfoState())
}

// 取消
function cancelOrderState () {
    // 关闭当前页面
    parent.layer.closeAll();
}

//
getData.orderData()

//验证只能输入数字，不能输入0
function Verificationall (val) {
    val.value = val.value.replace(/[^\d]/g, ""); //清除"数字"以外的字符
    val.value = val.value.replace(/^\./g, ""); //验证第一个字符是数字
    val.value = val.value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
    val.value = val.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    val.value = val.value.replace(/^[0]+[0-9]*$/gi, "")
}
/*//区域
regions();
function regions () {
    var selno = document.getElementById("priceAreaId");
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.goodsInter.goods_findSkuPriceArea,
        cache: false,  //禁用缓存
        dataType: "json",
        async: false,//优先运行
        success: function (obj) {

            for (var i = 0; i < obj.areaList.length; i++) {
                var option = new Option(obj.areaList[i].area_name, obj.areaList[i].price_area_id);
                selno.options.add(option)

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
        }
    });

}*/
//验证支付审批周期手动输入小于5的正整数，自动填充5，手动输入大于30的正整数，自动填充30
function effectiveness (val) {
    var datas = $(val).val()
    if (datas != "") {
        // 本次需要干掉编辑规则2021-11-10
        // if (Number(datas) < 5) {
        //     $(val).val(5)
        // }
        // if (Number(datas) > 30) {
        //     $(val).val(30)
        // }
    }

}

//选择轮播图不展示校验
function checkMianCustomerSlideshowIsShow () {
    var url = root.member.checkMianCustomerSlideshowIsShow + "?mainCustomerId=" + mainCustomerId;
    //var url = root.member.checkMianCustomerSlideshowIsShow + "?mainCustomerId=3085";
    $.post(url, function (data, status) {
        if (data.errorCode == 0) {
            if (!data.data) {
                $.Huimodalalert('未配置专属轮播图，请前往配置', 3000);
                $("#radio11").prop('checked', false);
                $("#radio10").prop('checked', true);
                return false;
            }
        } else {
            return false;
        }
    })
}


//--------------------------------------------------------------------------------------------------------------订单信息配置----------------------------------------------------------------------------------------
//订单配置保存
function saveMianCustomerOrderExtSetup () {
    var params = {
        attachment: $("input[name='attachment']:checked").val(),
        materielNumber: $("input[name='materielNumber']:checked").val(),
        materielName: $("input[name='materielName']:checked").val(),
        orderRemark: $("input[name='orderRemark']:checked").val(),
        outOrderId: $("input[name='outOrderId']:checked").val(),
        attachment: $("input[name='attachment']:checked").val(),
        type: "1",
        mainCustomerId: mainCustomerId,
        platform: "20",
        operateUserId: operateUserId,
        operateUserName: operateUserName,
        operateAccountName: operateAccountName
    };
    $.ajax({
        url: root.member.saveMianCustomerOrderExtSetup,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            if (data.errorCode === 0) {
                $.Huimodalalert('保存成功', 3000);
                // 关闭当前页面
                //parent.layer.closeAll();
                Get_MianCustomerOrderExtSetup();
            } else {
                $.Huimodalalert(data.msg, 3000);
            }
        },
        error: function (msg) {
            $.Huimodalalert(msg, 3000);
        }
    })
}

//订单信息配置展示
function Get_MianCustomerOrderExtSetup () {
    $("#attachment").attr("checked", true);
    $("#materielNumber").attr("checked", true);
    $("#materielName").attr("checked", true);
    $("#orderRemark").attr("checked", true);
    $("#outOrderId").attr("checked", true);

    var params = {
        mainCustomerId: mainCustomerId, type: 1
    }
    $.ajax({
        url: root.member.queryMainCustomerExtOrderSetup,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            console.log(data);
            if (data.errorCode === 0) {
                if (data.data != null && data.data != "") {
                    if (data.data.attachment == "10") {
                        $("#attachment_required").attr("checked", true);
                    }

                    if (data.data.materielNumber == "10") {
                        $("#materielNumber_required").attr("checked", true);
                    }

                    if (data.data.materielName == "10") {
                        $("#materielName_required").attr("checked", true);
                    }

                    if (data.data.orderRemark == "10") {
                        $("#orderRemark_required").attr("checked", true);
                    }

                    if (data.data.outOrderId == "10") {
                        $("#outOrderId_required").attr("checked", true);
                    }

                    var o_Last_Operation_User_Info = data.data.operateAccountName;
                    if (data.data.operateUserName != null && data.data.operateUserName != "") {
                        o_Last_Operation_User_Info += "(" + data.data.operateUserName + ")";
                    }
                    $(".o_Last_Operation_User_Info").html(o_Last_Operation_User_Info);
                    $(".o_last_Operation_Date").html(data.data.updateTime);
                }
            } else {
                $.Huimodalalert(data.msg, 3000);
            }
        },
        error: function (msg) {
            $.Huimodalalert(msg, 3000);
        }
    })
}



//--------------------------------------------------------------------------------------------------------------审批功能配置----------------------------------------------------------------------------------------


//审批功能配置保存
function saveMainCustomerApproveExtSetup () {
    var approveNotices = $('input:checkbox[name="approveNotice"]:checked');
    var refuseNotices = $('input:checkbox[name="refuseNotice"]:checked');
    var approveNotice = "";
    var refuseNotice = "";
    if (approveNotices.length > 0) {
        approveNotices.each(
            function (i, item) {
                approveNotice += $(item).val() + ",";
            }
        );
        approveNotice = approveNotice.substring(0, approveNotice.length - 1);
    }

    if (refuseNotices.length > 0) {
        refuseNotices.each(
            function (i, item) {
                refuseNotice += $(item).val() + ",";
            }
        );
        refuseNotice = refuseNotice.substring(0, refuseNotice.length - 1);
    }

    var params = {
        mainCustomerId: mainCustomerId,
        type: "2",
        approveNotice: approveNotice,
        refuseNotice: refuseNotice,
        platform: "20",
        operateUserId: operateUserId,
        operateUserName: operateUserName,
        operateAccountName: operateAccountName
    };
    $.ajax({
        url: root.member.saveMainCustomerApproveExtSetup,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            if (data.errorCode === 0) {
                $.Huimodalalert('保存成功', 3000);
                Get_MainCustomerApproveExtSetup();
                // 关闭当前页面
                //parent.layer.closeAll();
            } else {
                $.Huimodalalert(data.msg, 3000);
            }
        },
        error: function (msg) {
            $.Huimodalalert(msg, 3000);
        }
    })
}

//审批功能配置展示
function Get_MainCustomerApproveExtSetup () {
    $("input[name='approveNotice']").attr("checked", false);
    $("input[name='refuseNotice']").attr("checked", false);

    var params = {
        mainCustomerId: mainCustomerId, type: 2
    }
    $.ajax({
        url: root.member.queryMainCustomerExtOrderSetup,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            console.log(data);
            if (data.errorCode === 0) {
                if(data.data==null){
                    var lists=[1]
                    $("input[name='approveNotice']").val(lists);
                    $("input[name='refuseNotice']").val(lists);
                }else {
                    $("input[name='approveNotice']").val(data.data.approveNoticeList);
                    $("input[name='refuseNotice']").val(data.data.refuseNoticeList);
                    var o_Last_Operation_User_Info = data.data.operateAccountName;
                    if (data.data.operateUserName != null && data.data.operateUserName != "") {
                        o_Last_Operation_User_Info += "(" + data.data.operateUserName + ")";
                    }
                    $(".c_Last_Operation_User_Info").html(o_Last_Operation_User_Info);
                    $(".c_Last_Operation_Date").html(data.data.updateTime);
                }

            } else {
                $.Huimodalalert(data.msg, 3000);
            }
        },
        error: function (msg) {
            $.Huimodalalert(msg, 3000);
        }
    })
}